package com.seis_645.appTesting;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class AddressDataSource {

	// database fields
	private SQLiteDatabase database;
	private MySQLiteHelper db_helper;
	private String[] all_columns = {MySQLiteHelper.ADDR_ID, MySQLiteHelper.ADDR_STREET ,MySQLiteHelper.ADDR_CITY, MySQLiteHelper.ADDR_STATE, MySQLiteHelper.ADDR_ZIP};
	
	public AddressDataSource(Context context) {
		this.db_helper = new MySQLiteHelper(context);
	}
	
	public void open() throws SQLException {
		database = db_helper.getWritableDatabase();
	}
	
	public void close() {
		db_helper.close();
	}
	
	public Address create_address(String street,String city, String state, String zipcode) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.ADDR_STREET,street);
		values.put(MySQLiteHelper.ADDR_CITY,city);
		values.put(MySQLiteHelper.ADDR_STATE,state);
		values.put(MySQLiteHelper.ADDR_ZIP,zipcode);
		
		long insert_id = this.database.insert(MySQLiteHelper.TBL_ADDRESS, null, values);
		
		Cursor cursor = this.database.query(MySQLiteHelper.TBL_ADDRESS,this.all_columns,MySQLiteHelper.ADDR_ID + " = " + insert_id, null,null,null,null);
		cursor.moveToFirst();
		Address new_address = cursor_to_address(cursor);
		cursor.close();
		
		return new_address;
	}
	
	public Address get_address(long addr_id) {
		
		Cursor cursor = this.database.query(MySQLiteHelper.TBL_ADDRESS,
				all_columns, MySQLiteHelper.ADDR_ID + " = " + addr_id, null, null,
				null, null);
		cursor.moveToFirst();
		Address address = cursor_to_address(cursor);

		return address;
	}
	
	public void delete_address(Address addr) {
		long id = addr.get_id();
		System.out.println("Comment deleted with id: " + id);
		this.database.delete(MySQLiteHelper.TBL_ADDRESS, MySQLiteHelper.ADDR_ID + " = " + id, null);
	}
	
	public List<Address> get_all_addresses() {
		List<Address> addrs = new ArrayList<Address>();
		
		Cursor cursor = this.database.query(MySQLiteHelper.TBL_ADDRESS,all_columns,null,null,null,null,null);
		cursor.moveToFirst();
		while(!cursor.isAfterLast()) {
			Address addr = cursor_to_address(cursor);
			addrs.add(addr);
			cursor.moveToNext();
		}
		
		cursor.close();
		return addrs;
	}
	
	private Address cursor_to_address(Cursor cursor) {
		Address addr = new Address(cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4));
		addr.set_id(cursor.getLong(0));
		return addr;
	}
}
